// pages/order/order.js
import { reqGetShopList, reqApplyRefund,confirmGoodsMenthod,deleteGoodsMenthod } from '../../api/shop';
import { toast } from '../../utils/extendApi';
import { getStorage } from '../../utils/storage';
Page({
  data: {
    activeTab: 0,
    allOrders: [],
    ongoingOrders: [],
    pendingOrders: [],
    refundOrders: [],
    loading: true,
    userinfo:'',
    iflogin:'',//判断是否登录
     showRefundDialog: false, // 控制弹窗显示
    refundReason: '',        // 存储退款理由
    currentRefundOrderId: '',// 存储当前申请退款的订单 ID
  },

  // 切换选项卡
  onChange(event) {
    this.setData({
      activeTab: event.detail.index
    });
  },
// 确认收货按钮 
confirmGoods(e) {
    const orderId = e.currentTarget.dataset.id;
    console.log("确认收货得到的订单id：" + orderId);

    // 微信小程序的确认弹窗
    wx.showModal({
      title: '确认收货',
      content: '你确定已经收到货了吗？点击确认将执行确认收货操作',
      success: (res) => {
        if (res.confirm) { // 用户点击了确认
          confirmGoodsMenthod(orderId).then((result) => {
            if (result>0) {
              wx.showToast({
                title: '确认收货操作成功',
                icon: 'success'
              });
              // 刷新订单信息
              this.fetchshops();
            } else {
              wx.showToast({
                title: '确认收货操作失败，请稍后重试',
                icon: 'none'
              });
            }
          }).catch((error) => {
            console.error('确认收货操作出错：', error);
            wx.showToast({
              title: '确认收货操作出错，请稍后重试',
              icon: 'none'
            });
          });
        } else { // 用户点击了取消
          console.log('用户取消了确认收货操作');
        }
      }
    });
  },
  // 删除订单
  deleteOrders(e){
    const orderId = e.currentTarget.dataset.id;
    console.log("删除订单得到的订单id：" + orderId);

    // 微信小程序的确认弹窗
    wx.showModal({
      title: '确认删除',
      content: '你确认要删除这个订单吗',
      success: (res) => {
        if (res.confirm) { // 用户点击了确认
            deleteGoodsMenthod(orderId).then((result) => {
            if (result>0) {
              wx.showToast({
                title: '删除订单操作成功',
                icon: 'success'
              });
              // 刷新订单信息
              this.fetchshops();
            } else {
              wx.showToast({
                title: '删除订单操作失败，请稍后重试',
                icon: 'none'
              });
            }
          }).catch((error) => {
            console.error('删除订单操作出错：', error);
            wx.showToast({
              title: '删除订单操作出错，请稍后重试',
              icon: 'none'
            });
          });
        } else { // 用户点击了取消
          console.log('用户取消了删除订单操作');
        }
      }
    });
  },
  // 评价
  evaluate(e) {
    const orderId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/gojudge/gojudge?orderId=${orderId}`,
    })
  },
// 输入退款理由时更新数据
  onRefundReasonInput(e) {
    console.log('输入框内容：', e.detail); // 必看！输入时是否有日志
        this.setData({ refundReason: e.detail });
  },

  // 取消退款申请：关闭弹窗
  closeRefundDialog() {
    this.setData({ showRefundDialog: false });
  },

  // 确认退款申请：调用接口 + 关闭弹窗
confirmRefund() {
    const { currentRefundOrderId, refundReason } = this.data;
    console.log('当前退款理由:', refundReason); // 调试用
    
    // 更严格的验证
    if (!refundReason || typeof refundReason !== 'string' || refundReason.trim().length === 0) {
      toast({ title: '请输入有效的退款理由' });
      return;
    }
    
    // 调用退款接口
    this.requestRefund(currentRefundOrderId, refundReason.trim());
    
    // 清空输入框并关闭弹窗
    this.setData({
      showRefundDialog: false,
      refundReason: ''
    });
  },
 // 触发申请退款流程：显示弹窗 + 记录订单 ID
 applyRefund(e) {
    const orderId = e.currentTarget.dataset.id;
    this.setData({
      showRefundDialog: true,
      currentRefundOrderId: orderId,
      refundReason: this.data.refundReason || '' // 重置输入框
    });
  },
  // 原 requestRefund 方法（接收退款理由参数）
  requestRefund(orderId, userreason) {
    wx.showLoading({ title: '申请退款中...' });
    reqApplyRefund(orderId, userreason)
      .then(res => {
        wx.hideLoading();
        if (res === 1) {
          wx.showToast({ title: '已提交退款申请', icon: 'success' });
          this.fetchshops();
        } else {
          wx.showToast({ title: res.msgerr || '退款申请失败', icon: 'none' });
        }
      })
      .catch(err => {
        wx.hideLoading();
        console.error('申请退款失败:', err);
        wx.showToast({ title: err.message || '申请退款失败', icon: 'none' });
      });
  },
  // 加载订单数据
  fetchshops: function() {
       // 从本地存储中获取用户信息
       const userInfo = wx.getStorageSync('userinfo');
       if (!userInfo || !userInfo.userid) {
         wx.showToast({
           title: '未获取到用户信息',
           icon: 'none'
         });
         return;
       }
       // 从用户信息中获取 userid
       const userId = userInfo.userid;
       console.log("订单页面获取到的userid：")
       console.log(userId);
     reqGetShopList(userId) 
      .then(res => {
        console.log("API响应:", res);
        if (res.code === 200) {
          const orders = res.data.ordercakeList || [];
          console.log("原始订单数据:", orders);
          
          // 处理订单数据
          const processedOrders = this.processOrderData(orders);
          
          this.setData({
            allOrders: processedOrders.allOrders,
            ongoingOrders: processedOrders.ongoingOrders,
            pendingOrders: processedOrders.pendingOrders,
            refundOrders: processedOrders.refundOrders,
            loading: false
          });
        } else {
          throw new Error(res.msgerr || '加载订单失败');
        }
      })
      .catch(err => {
        console.error('加载订单失败:', err);
        wx.showToast({
          title: err.message || '加载订单失败',
          icon: 'none'
        });
        this.setData({ loading: false });
      });
  },

// 处理订单数据
processOrderData(orders) {
    const allOrders = [];
    const ongoingOrders = [];
    const pendingOrders = [];
    const refundOrders = [];
    
    orders.forEach(order => {
      // 转换数据结构（保持不变）
      const orderData = {
        id: order.orderid,
        cakes: order.cakes,
        ordernum: order.ordernum,
        ordertime: order.ordertime,
        status: this.getStatusText(order.orderstatus, order.refund),
        products: [{
          id: order.cakeid || 0,
          name: order.cakename || '未知商品',
          price: order.orderprice || 0,
          image: order.cakeurl || '/images/default-product.png',
          count: order.orderecount || 1
        }],
        canRefund: order.refund === 0 && this.isWithinDays(order.ordertime, 3)
      };
      
      allOrders.push(orderData);
      
      // 关键修改：移除 else if，使用独立判断，让订单可以同时属于多个分类
      if ((order.orderstatus === 1 || order.orderstatus === 2 )&& order.refund === 0) { // 进行中订单【状态为1：待配送 和2：待收货 并且退款状态要为 未退款】
        ongoingOrders.push(orderData);
      }
       // 待评价的【状态为3：已完成和orderdiscussif为0未评价的情况】
      if (order.orderstatus === 3 && order.orderdiscussif === 0) {
        pendingOrders.push(orderData);
      }
      // 售后订单判断（独立于其他分类）【售后的条件为状态为1,2，3  并且时间在三天以内，退款状态为0未退款的】
      if (order.refund === 0 && this.isWithinDays(order.ordertime, 3) &&order.orderstatus === 3 ||order.orderstatus === 2 || order.orderstatus === 1 ) {
        refundOrders.push(orderData);
        console.log('售后订单:', orderData); // 调试用
      }
    });
    
    return { allOrders, ongoingOrders, pendingOrders, refundOrders };
  },
  
  /**
   * 跳转到订单详情页
   * @param {Object} e 事件对象
   */
  navigateToOrderDetail: function(e) {
    const orderId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/orderdetail/orderdetail?orderId=${orderId}`,
    });
  },
  


  // 检查是否在指定天数内
  isWithinDays(dateString, days) {
    if (!dateString) return false;
    const orderDate = new Date(dateString);
    const diffTime = Math.abs(new Date() - orderDate);
    const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24)); 
    return diffDays <= days;
  },

  // 获取状态文本
  getStatusText(status, refund) {
    const statusMap = {
      0: '待修改',
      1: '待配送',
      2: '待收货', 
      3: '已完成'
    };
    
    if (refund === 1) return '退款中';
    if (refund === 2) return '已退款';
    
    return statusMap[status] || '未知状态';
  },

  onLoad: function() {
    this.fetchshops();
  },
  onShow(){
    this.fetchshops();
    this.setData({
      userinfo: getStorage("userinfo"),
      iflogin:getStorage("iflogin"),
    })
    if(!this.data.iflogin){
      //跳转到登录页面
      toast({ title: '登录过后再进行此操作',duration:500});
      setTimeout(() => {
        // 新增地址成功后，返回地址
        wx.switchTab({
          url: '/pages/owner/owner',
        })
      }, 700);
      return;
    }
  },

  onPullDownRefresh() {
    this.fetchshops(() => {
      wx.stopPullDownRefresh();
    });
  }
});